using System;
using System.Windows.Forms;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace Weather
{
    public partial class WeatherForm : Form
    {
        private Label lblWeather; // 显示天气状况
        private Label lblTemperature; // 显ao示温度
        private Label lblHumidity; // 显示湿度
        private Label lblWind; // 显示风向
        private Button btnRefresh; // 刷新天气
        private ComboBox cmbCity; // 选择城市下拉选框
        
        // 高德API密钥 
        private const string API_KEY = AppConfig.WeatherApiKey;
      
        public WeatherForm()
        {
            InitializeComponents();
            _ = LoadWeatherAsync();
        }

        private void InitializeComponents()
        {
            this.Size = new Size(800, 600);
            this.BackColor = Color.White;
            this.Padding = new Padding(20);

            // 创建主面板
            var mainPanel = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.White,
                Padding = new Padding(20)
            };

            // 创建城市选择和刷新按钮的面板
            var topPanel = new Panel
            {
                Dock = DockStyle.Top,
                Height = 60,
                Padding = new Padding(0, 0, 0, 10)
            };

            cmbCity = new ComboBox
            {
                Location = new Point(0, 15),
                Size = new Size(200, 35),
                DropDownStyle = ComboBoxStyle.DropDownList,
                Font = new Font("Microsoft YaHei", 12),
                FlatStyle = FlatStyle.Flat
            };

            // 添加更多城市
            cmbCity.Items.AddRange(new string[] { 
                "上海,310000", 
                "北京,110000", 
                "广州,440100",
                "深圳,440300",
                "杭州,330100",
                "南京,320100",
                "成都,510100",
                "重庆,500000",
                "武汉,420100",
                "西安,610100",
                "苏州,320500",
                "天津,120000",
                "长沙,430100",
                "郑州,410100",
                "青岛,370200"
            });
            cmbCity.SelectedIndex = 0;
            cmbCity.SelectedIndexChanged += CmbCity_SelectedIndexChanged;

            btnRefresh = new Button
            {
                Text = "刷新天气",
                Location = new Point(220, 15),
                Size = new Size(100, 35),
                FlatStyle = FlatStyle.Flat,
                BackColor = Color.FromArgb(72, 190, 117),
                ForeColor = Color.White,
                Font = new Font("Microsoft YaHei", 10),
                Cursor = Cursors.Hand
            };
            btnRefresh.FlatAppearance.BorderSize = 0;
            btnRefresh.Click += BtnRefresh_Click;

            topPanel.Controls.AddRange(new Control[] { cmbCity, btnRefresh });

            // 创建天气信息显示面板
            var weatherPanel = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.FromArgb(245, 247, 250),
                Padding = new Padding(30)
            };

            // 天气信息标签
            lblWeather = new Label
            {
                AutoSize = true,
                Font = new Font("Microsoft YaHei", 24, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64),
                Location = new Point(30, 30)
            };

            lblTemperature = new Label
            {
                AutoSize = true,
                Font = new Font("Microsoft YaHei", 36),
                ForeColor = Color.FromArgb(72, 190, 117),
                Location = new Point(30, 90)
            };

            lblHumidity = new Label
            {
                AutoSize = true,
                Font = new Font("Microsoft YaHei", 14),
                ForeColor = Color.FromArgb(128, 128, 128),
                Location = new Point(30, 170)
            };

            lblWind = new Label
            {
                AutoSize = true,
                Font = new Font("Microsoft YaHei", 14),
                ForeColor = Color.FromArgb(128, 128, 128),
                Location = new Point(30, 210)
            };

            // 添加更新时间标签
            var lblUpdateTime = new Label
            {
                AutoSize = true,
                Font = new Font("Microsoft YaHei", 10),
                ForeColor = Color.FromArgb(160, 160, 160),
                Location = new Point(30, 250)
            };
            lblUpdateTime.Text = $"更新时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss}";

            weatherPanel.Controls.AddRange(new Control[] { 
                lblWeather, 
                lblTemperature, 
                lblHumidity, 
                lblWind,
                lblUpdateTime
            });

            // 添加面板到主窗体
            mainPanel.Controls.Add(weatherPanel);
            mainPanel.Controls.Add(topPanel);
            this.Controls.Add(mainPanel);

            // 初始加载天气
            _ = LoadWeatherAsync();
        }

        private async void CmbCity_SelectedIndexChanged(object sender, EventArgs e)
        {
            await LoadWeatherAsync();
        }

        private async Task LoadWeatherAsync()
        {
            try
            {
                var weather = await GetWeatherAsync();
                UpdateWeatherDisplay(weather);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取天气信息失败：{ex.Message}");
            }
        }

        private async Task<JObject> GetWeatherAsync()
        {
            using (var client = new HttpClient())
            {
                string cityCode = GetSelectedCityCode();
                string url = $"https://restapi.amap.com/v3/weather/weatherInfo?key={API_KEY}&city={cityCode}&extensions=all";
                var response = await client.GetStringAsync(url);
                return JObject.Parse(response);
            }
        }

        private void UpdateWeatherDisplay(JObject weatherData)
        {
            try 
            {
                var forecast = weatherData["forecasts"][0]["casts"][0];
                var weather = forecast["dayweather"].ToString();
                var dayTemp = forecast["daytemp"].ToString();
                var nightTemp = forecast["nighttemp"].ToString();
                var windDir = forecast["daywind"].ToString();
                var windPower = forecast["daypower"].ToString();

                // 使用更友好的显示格式
                lblWeather.Text = $"天气：{weather}";
                lblTemperature.Text = $"温度：{nightTemp}°C ~ {dayTemp}°C";
                lblWind.Text = $"风向：{windDir} {windPower}级";
                lblHumidity.Text = $"更新时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss}";

                // 根据天气状况设置不同的图标或颜色
                if (weather.Contains("晴"))
                {
                    lblWeather.ForeColor = Color.FromArgb(255, 165, 0); // 橙色
                }
                else if (weather.Contains("雨"))
                {
                    lblWeather.ForeColor = Color.FromArgb(30, 144, 255); // 蓝色
                }
                else if (weather.Contains("阴"))
                {
                    lblWeather.ForeColor = Color.FromArgb(128, 128, 128); // 灰色
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"解析天气数据失败：{ex.Message}");
            }
        }

        private string GetSelectedCityCode()
        {
            string selected = cmbCity.SelectedItem.ToString();
            return selected.Split(',')[1];
        }

        private async void BtnRefresh_Click(object sender, EventArgs e)
        {
            await LoadWeatherAsync();
        }
    }
} 